//
//  FloatIcon.m
//  auction2
//
//  Created by eqidian1 on 2018/8/29.
//  Copyright © 2018年 muxia. All rights reserved.
//

#import "JMFloatIcon.h"

@implementation JMFloatIcon
{
    CGPoint startLocation;
}
singleton_implementation(JMFloatIcon)

- (instancetype)initWithFrame:(CGRect)frame {
    if ([super initWithFrame:frame]) {
        self.contentMode = UIViewContentModeScaleAspectFit;
        self.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapMe)];
        [self addGestureRecognizer:tap];
//        [self addCloseBtn];
    }
    return self;
}

- (void)addCloseBtn {
    UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    closeBtn.frame = CGRectMake(0, 0, self.frame.size.width, 20);
    [closeBtn addTarget:self action:@selector(tapClose) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:closeBtn];
}

#pragma mark -

- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
    CGPoint pt = [[touches anyObject] locationInView:self];
    startLocation = pt;
    [[self superview] bringSubviewToFront:self];
}

- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {
    CGPoint pt = [[touches anyObject] locationInView:self];
    float dx = pt.x - startLocation.x;
    float dy = pt.y - startLocation.y;
    CGPoint newcenter = CGPointMake(self.center.x + dx, self.center.y + dy);
    //
    float halfx = CGRectGetMidX(self.bounds);
    newcenter.x = MAX(halfx, newcenter.x);
    newcenter.x = MIN(self.superview.bounds.size.width - halfx, newcenter.x);
    //
    float halfy = CGRectGetMidY(self.bounds);
    newcenter.y = MAX(halfy, newcenter.y);
    newcenter.y = MIN(self.superview.bounds.size.height - halfy, newcenter.y);
    //
    self.center = newcenter;
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    CGPoint point = self.center;
    if (point.x>[self superview].width/2.0) {
        [UIView animateWithDuration:0.2 animations:^{
            self.left = [self superview].width-self.width;
            if (point.y>=kAppH()-TAB_BAR_HEIGHT()) {
                self.top = kAppH()-TAB_BAR_HEIGHT()-self.height;
            }
            if(point.y<=kSafeAreaTopHeight()){
                self.top = kSafeAreaTopHeight();
            }
        }];
        
    }else{
        [UIView animateWithDuration:0.2 animations:^{
            self.left =0;

            if (point.y>=kAppH()-TAB_BAR_HEIGHT()) {
                self.top = kAppH()-TAB_BAR_HEIGHT()-self.height;
            }
            if(point.y<=kSafeAreaTopHeight()){
                self.top = kSafeAreaTopHeight();
            }
        }];
    }
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
}

#pragma mark -
- (void)tapMe {
    NSLog(@"touch float icon ....");
//    [FirstConfig.floatModel doModelEvent];
}

- (void)tapClose {
    self.hidden = YES;
}

@end
